﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Ornament;
using System.IO;

namespace Ornament.Messages.Contents.Stores
{
    public class FileStore : IStore
    {
        string parentPath;
        /// <summary>
        /// 
        /// </summary>
        public FileStore(string mainFolder)
        {
            this.parentPath = mainFolder;

            if (mainFolder.StartsWith("~"))
            {
                parentPath = parentPath.Replace("~", AppDomain.CurrentDomain.BaseDirectory);
            }
            else if (mainFolder.StartsWith("/") || mainFolder.StartsWith("\\"))
            {
                parentPath = AppDomain.CurrentDomain.BaseDirectory + parentPath;
            }
            else
            {
                parentPath = AppDomain.CurrentDomain.BaseDirectory;
            }

            this.parentPath = Path.Combine(parentPath, "Data");

            if (!Directory.Exists(parentPath))
            {
                Directory.CreateDirectory(parentPath);
            }

        }
        #region IStore Members

        public virtual void Write(Info info)
        {
            string filePath = Path.Combine(parentPath, info.Id.ToString());
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            using (var w = new StreamWriter(Path.Combine(filePath, "content.txt")))
            {
                w.Write(info.Content.ToString());
            }
        }

        public virtual void ReadIn(Info info)
        {
            string filePath = Path.Combine(parentPath, info.Id.ToString());
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            using (var w = new StreamReader(Path.Combine(filePath, "content.txt")))
            {
                info.Content.Value = w.ReadToEnd();
            }
        }



        public void Delete(Info info)
        {
            string filePath = Path.Combine(parentPath, info.Id.ToString());
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath, true);
            }
        }

        #endregion
    }
}
